﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Security;
using System.Collections;
using iLangl.BusinessModel.DAL;
using System.Web.Security;
using System.Web.Profile;

namespace iLangl.BusinessModel.Managers
{
	public class AuthenticationManager : BaseManager
	{

		Hashtable sessions;
		#region Singelton Pattern
		public AuthenticationManager()
		{
			sessions = new Hashtable();
		}

		private static AuthenticationManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the AuthenticationManager.
		/// </summary>
		public static AuthenticationManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new AuthenticationManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public MembershipUser GetUserId(String userId)
		{
			return Membership.GetUser(new Guid(userId));
		}

		public void AssignContactIdToUserAccount(string username, string contactId)
		{

			ProfileBase pb = DefaultProfile.Create(username);
			pb.SetPropertyValue("ContactId", contactId);
			pb.Save();

		}

		public void AssignContactIdToUserAccountId(string userId, string contactId)
		{
			ProfileBase pb = DefaultProfile.Create(GetUserId(userId).UserName);
			pb.SetPropertyValue("ContactId", contactId);
			pb.Save();

		}

		public String CreateSession(Guid userId)
		{
			AuthenticationServiceDAL dal = new AuthenticationServiceDAL();
			return dal.CreateSession(userId);
		}

		public String ReadContactIdByUserAccount(string username)
		{
			ProfileBase pb = DefaultProfile.Create(username);

			return (String)pb.GetPropertyValue("ContactId");
		}

		public String ReadContactIdByUserAccountId(string userId)
		{
			MembershipUser mu =  Membership.GetUser(new Guid(userId));

			return ReadContactIdByUserAccount(mu.UserName);
		}
	}
}
